import http from './http';
import store from '@/store';
function Utils(){
    this.checkLogin = () =>{
        let access_token = store.state.access_token;
        if(!access_token){
          this.gotoLogin("请先登录");
          return false;
        }
        return true;
    };
    this.gotoLogin = (tips) => {
      uni.showModal({
        title: '提示',
        content: tips,
        success: res => {
            if (res.confirm) {
              let pages = getCurrentPages();
              uni.removeStorageSync('access_token');
              uni.setStorageSync('before_login', pages[pages.length - 1].$page.fullPath);
              uni.navigateTo({
                url: '/pages/login/index'
              });
              store.commit('setUserInfo', null);
              store.commit('setVipInfo', null);
              store.commit('setShowMsgBox', false);
              uni.removeStorageSync('userInfo')
              uni.removeStorageSync('vipInfo')
            } else if (res.cancel) {
              uni.switchTab({
                url: '/pages/index/index'
              });
              store.commit('setShowMsgBox', false);
            }
        }
      });
      
    }
    this.resetForm = (form, reset_form) => {
      let obj = JSON.parse(JSON.stringify(reset_form));
      for(var key in form){
          if(reset_form.hasOwnProperty(key)){
              form[key] = obj[key];
          };
      }
    };

    //数组格式转化
    this.transformArray = (arr, idKey, nameKey) => {
      let id = idKey || 'value';
      let name = nameKey || 'label';
      let data = [];
      if(arr.length  > 0){
          data = arr.map(item => {return {id: item[id], name: item[name]}});
      }else{
          data = []
      }
      return data;
  },
    // 时间格式兼容性转换
    this.getTime = (data) => {
      let new_date = data.replace(/-/g,"/");
      let time = new Date(new_date).getTime();
      return time;
    };

    // 序列化转为对象
    this.format = (str) => {
        let arr = str.split('&');
        let obj = {};
        arr.forEach(item => {
            let item_arr = item.split('=')
            obj[item_arr[0]] = item_arr[1];
        });
        return obj;
    };

    // 对象转为序列化
    this.serialize = (obj) => {
        let str = '?';
        for(let key in obj){
            str += key + '=' + obj[key] + '&';
        };
        return str.slice(0, str.length-1);
    };
    // 将毫秒转为时分秒
    this.formatDuring = (mss) => {
      var days = parseInt(mss / (1000 * 60 * 60 * 24));
      var hours = parseInt((mss % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      var minutes = parseInt((mss % (1000 * 60 * 60)) / (1000 * 60));
      var seconds = Math.floor((mss % (1000 * 60)) / 1000);
      let str = '';
      if(hours == 0){
          str = minutes + "分钟 " + seconds + "秒 ";
      }else{
          str = hours + '小时' + minutes + "分钟" + seconds + "秒 ";
      }
      if(hours == 0 && minutes == 0){
          str = seconds + '秒'
      }
      return str;
    };

  this.validatenull = (val) => {
    if (typeof val === 'boolean') {
      return false
    }
    if (typeof val === 'number') {
      return false
    }
    if (val instanceof Array) {
      if (val.length == 0) return true
    } else if (val instanceof Object) {
      if (JSON.stringify(val) === '{}') return true
    } else {
      if (val == 'null' || val == null || val == 'undefined' || val == undefined || val == '') return true
      return false
    }
    return false
  };

  // 用于小程序二维码入口参数解析
  this.parseScene = (scene) => { // id,来源id,来源类型
    if(!scene)return {}
    let data = {}
    let arr = decodeURIComponent(scene).split(",")
    if(arr)data.scene = arr
    if(arr.length) data.id = arr[0]
    if(arr.length>1) data.source = arr[1]
    if(arr.length>2) data.sourceType = arr[2]
    return data
  };

  this.gotoPage = (url, param) => {
    let new_url = url;
    if(param){
      new_url += this.serialize(param);
    }
    uni.navigateTo({
       url: new_url
    })
  };

  this.getParam = (data) => {
    let search_param = {};
    for(let key in data){
      if(data[key] != null && String(data[key]).trim() != ''){
        search_param[key] = data[key];
      }
    }
    return search_param;
  };

  // 获取名字
  this.setName = (id, list) => {
    let name = '未知';
    let arr = list.filter(item => item.id == id);
    if(arr.length == 1){
        name = arr[0].name;
    }
    return name;          
  }

  //获取随机字符串
  this.randomStr = (len) => {
    let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    let maxPros = chars.length;
    let str = '';
    for(let i=0; i<len; i++){
      str += chars.charAt(Math.floor(Math.random()*maxPros))
    }
    return str;
  }

  // 字符串过长截取
  this.getEllipsis = (val, length) => {
    let str = val+'';
    let len = length || 15;
    if(str.length > len){
      return str.substring(0,len) + '...'
    }else{
      return val;
    }
  }

  // 计算两个经纬度的距离
  this.getDistance = ( lat1,  lng1,  lat2,  lng2) => {
    if(!lat1 || !lng1 || !lat2 || !lng2){
      return null;
    }
    var radLat1 = Number(lat1)*Math.PI / 180.0;
    var radLat2 = Number(lat2)*Math.PI / 180.0;
    var a = radLat1 - radLat2;
    var  b = lng1*Math.PI / 180.0 - Number(lng2)*Math.PI / 180.0;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a/2),2) +
    Math.cos(radLat1)*Math.cos(radLat2)*Math.pow(Math.sin(b/2),2)));
    s = s *6378.137 ;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000;
    return s.toFixed(2);
  }

  // 获取星期几
  this.getWeek = (week) => {
    let str;
    switch(week){
      case 0 :
        str = '日';
        break;
      case 1: 
        str = '一';
        break;
      case 2:
        str = '二';
        break;
      case 3:
        str = '三';
        break;
      case 4: 
        str = '四';
        break;
      case 5: 
        str = '五';
        break;
      case 6: 
        str = '六';
        break;
    }
    return str;
  }
}

export default new Utils();